<template>
    <div>
      <div style="margin: 10px 0;">
        <el-form :rules="queryForm" ref="queryForm" :model="queryForm">
            <el-input style="width: 230px;" placeholder="请输入名称" suffix-icon="el-icon-search" v-model="queryForm.userName"></el-input>
            <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
            <el-button type="warning" @click="reset">重置</el-button>
        </el-form>
      </div>

      <div style="margin: 10px 0;">
        <el-button type="primary" plain @click="handelAdd"><i class="el-icon-circle-plus-outline"></i> 新增</el-button>
        <!-- <el-popconfirm
            class="ml-5"
            confirm-button-text='确定'
            cancel-button-text='我再想想'
            icon="el-icon-info"
            icon-color="red"
            title="您确定批量删除这些数据吗"
            @confirm="delBatch"
            >
        <el-button type="danger" slot="reference">批量删除<i class="el-icon-remove-outline"></i></el-button>
        </el-popconfirm> -->
        <!-- <el-upload action="http://localhost:8081/user/import" :show-file-list="false" accept="xlsx" :on-success="handleExcelImportSuccess"	 style="display: inline-block;">
        <el-button type="danger" class="ml-5">导入<i class="el-icon-bottom"></i></el-button>
        </el-upload>
        <el-button type="danger" class="ml-5" @click="exp">导出<i class="el-icon-top"></i></el-button> -->
      </div>
      
      <el-table :data="tableData"  :header-cell-class-name="'headerBg'" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <!-- <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column> -->
        <el-table-column prop="avatarUrl" label="头像" align="center">
          <template slot-scope="scope">
            <el-image style="width: 100px; height: 100px" :src="'http://101.43.223.224:8765/image/getImageById?id=' + scope.row.avatarUrl">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="用户名" align="center"></el-table-column>
        <el-table-column prop="role" label="角色" align="center">
          <template slot-scope="scope">
            <el-tag type="" v-if="scope.row.role === 'ROLE_ADMIN'">系统管理员</el-tag>
            <el-tag type="" v-if="scope.row.role === 'ROLE_TEACHER'">教师</el-tag>
            <el-tag type="" v-if="scope.row.role === 'ROLE_AUDIT'">审核员</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="nickName" label="昵称" align="center"></el-table-column>
        <el-table-column prop="email" label="邮箱" align="center"></el-table-column>
        <el-table-column prop="isDisable" label="禁用/启用" align="center">
        <template v-slot="scope">
          <el-switch 
          v-model="scope.row.isDisable" 
          active-color="#13ce66" 
          inactive-color="#ff4949" 
          active-value=0 
          inactive-value=1
          @change="changeEnable(scope.row)" >
        </el-switch>
        </template>
      </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
        <el-table-column label="操作" width="400" align="center">
          <template slot-scope="scope"> 
            <el-button type="text" size="mini" @click="handelEditck(scope.row)"><i class="el-icon-share"></i>查看</el-button>
            <el-button type="text" size="mini" @click="handelEdit(scope.row)"><i class="el-icon-edit"></i>编辑</el-button>
            <el-popconfirm
              class="ml-5"
              confirm-button-text='确定'
              cancel-button-text='我再想想'
              icon="el-icon-info"
              icon-color="red"
              title="您确定删除这些数据吗"
              @confirm="del(scope.row.id)"
              >
            <el-button type="text" size="mini" slot="reference"><i class="el-icon-delete"></i>删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      
      <div style="padding: 10px 0;">
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
      </el-pagination>
      </div>

      <!-- 添加框 -->
      <el-dialog title="用户信息" :visible.sync="dialogFormVisible" width="25%">
        <el-form label-width="100px" size="small" ref="form" :model="form" :inline="true" :rules="rules">
          <el-input v-model="form.id" placeholder="id" type="hidden"></el-input>
          <el-form-item label="头像">
            <el-upload style=" margin-left: 19%" action="123123123" list-type="picture-card" class="upload-demo" :show-file-list="false" :before-upload="beforeAvatarUpload">
              <img height="148" v-if="avatarUrl" :src="avatarUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="用户名">
          <el-input v-model="form.userName" autocomplete="off" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select clearable v-model="form.role" placeholder="请选择角色" style="width: 200px;">
            <el-option v-for="item in roles" :key="item.roleName" :label="item.roleName" :value="item.flag"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="form.nickName" autocomplete="off" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="性别">
            <el-select v-model="form.gender" placeholder="请选择" style="width: 200px;">
              <el-option label="男" value="1"></el-option>
              <el-option label="女" value="2"></el-option>
            </el-select>
          </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" autocomplete="off" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="form.phone" autocomplete="off" placeholder="请输入电话" :maxlength="11" show-word-limit clearable style="width: 200px;"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="form.address" autocomplete="off" placeholder="请填写地址"></el-input>
        </el-form-item>
        
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 修改框 -->
      <el-dialog title="用户信息" :visible.sync="dialogFormVisibles" width="25%">
        <el-form label-width="100px" size="small" ref="form" :model="form" :rules="rules" :inline="true">
          <el-input v-model="form.id" placeholder="id" type="hidden"></el-input>
          <el-form-item label="头像">
            <el-upload style=" margin-left: 19%" action="123123123" list-type="picture-card" class="upload-demo" :show-file-list="false" :before-upload="beforeAvatarUpload">
              <img height="148" v-if="avatarUrl" :src="avatarUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="用户名">
          <el-input v-model="form.userName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select clearable v-model="form.role" placeholder="请选择角色" style="width: 200px;">
            <el-option v-for="item in roles" :key="item.roleName" :label="item.roleName" :value="item.flag"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="form.nickName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别：">
            <el-select v-model="form.gender" placeholder="请选择" style="width: 200px;">
              <el-option label="男" value="1"></el-option>
              <el-option label="女" value="2"></el-option>
            </el-select>
          </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" autocomplete="off" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="form.phone" autocomplete="off" placeholder="请输入电话" :maxlength="11" show-word-limit clearable style="width: 200px;"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="form.address" autocomplete="off"></el-input>
        </el-form-item>
        
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisibles = false">取 消</el-button>
          <el-button type="primary" @click="update">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 查看框 -->
      <el-dialog title="用户信息" :visible.sync="dialogFormVisibleck" width="25%">
        <el-form label-width="100px" size="small" ref="form" :model="form" :rules="form" :inline="true">
          <el-input v-model="form.id" placeholder="id" type="hidden"></el-input>
          <el-form-item label="头像">
              <img height="148" :src="avatarUrl" class="avatar" />
          </el-form-item>
          <el-form-item label="用户名">
          <el-input v-model="form.userName" autocomplete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select clearable v-model="form.role" placeholder="请选择角色" style="width: 200px;" :disabled="true">
            <el-option v-for="item in roles" :key="item.roleName" :label="item.roleName" :value="item.flag"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="form.nickName" autocomplete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="性别：">
            <el-select v-model="form.gender" placeholder="请选择" style="width: 200px;" :disabled="true">
              <el-option label="男" value="1"></el-option>
              <el-option label="女" value="2"></el-option>
            </el-select>
          </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="form.email" 
          autocomplete="off" 
          :disabled="true" 
          placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="form.phone" autocomplete="off" :disabled="true" placeholder="请输入手机号" :maxlength="11" show-word-limit clearable style="width: 200px;"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="form.address" autocomplete="off" :disabled="true"></el-input>
        </el-form-item>
        
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisibleck = false">取 消</el-button>
        </div>
      </el-dialog>

    </div>
</template>

<script>
import axios from 'axios'
import { Form } from 'element-ui'
export default {
    name: 'User',
    data() {
     return {
      isDisable: true,
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 5,
      dialogFormVisible: false,
      dialogFormVisibles: false,
      dialogFormVisibleck: false,
      form:{},
      queryForm:{
        userName: '',
      },
      multipleSelection : [],
      roles: [],
      value: '',//类型
       // 图片回显
       avatarUrl: "",
       //添加时赋值
       Urlavatar: "",
      rules: {
        phone: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
          {
            pattern: /^1(3|4|5|7|8|9)\d{9}$/,
            message: "手机号格式错误",
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur",
          },
          {
            pattern: /^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/,
            message: "邮箱格式错误",
            trigger: "blur",
          },
        ],
      },
     }
    },
    created(){
    //请求分页查询
    this.load()
  },
    methods: {
      load(){
      this.request.get("/User/SysUserList",{
        params:{
          pageNum:this.pageNum,
          pageSize:this.pageSize,
          userName:this.queryForm.userName,
        }
      }).then(res => {
        // console.log(res);
        this.tableData = res.data.content
        this.total = res.data.totalSize
      })
      this.request.get("/Role/RoleList").then(res => {
        this.roles = res.data.content
      })
  },
  // 文件上传校验
  beforeAvatarUpload(file) {
      //上传图片格式
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG && !isPNG) {
        this.$message.error("上传图片只能是JPG/PNG格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过2MB!");
        return false;
      }
      //赋值
      this.Urlavatar = file;
      this.avatarUrl = URL.createObjectURL(file);
      //isJPG && isLt2M 自动提交 false 是点击确定后提交
      return false;
    },
  save() {
  this.$refs['form'].validate((valid) => {
    if (valid) {
      const formData = new FormData();
      // 校验通过，执行保存修改操作
      // 图片
      for (const key in this.form) {
            formData.set(key, this.form[key]);
            formData.get(key);
        }
        if (this.Urlavatar) {
          formData.set("file", this.Urlavatar, this.Urlavatar.name);
        }
        
      this.$axios.post("/User/SysUserAdd",formData).then(res => {
        if (res) {
          this.$message.success("保存成功")
          this.avatarUrl = ""
          this.dialogFormVisible = false
          this.load()
        } else {
          this.$message.error("保存失败")
        }
      })
    } else {
      // 校验失败，不执行保存修改操作
    }
  });
},
update() {
  this.$refs['form'].validate((valid) => {
    if (valid) {
        // 图片
        const formData = new FormData();
        // 校验通过，执行修改操作
        formData.set("id", this.form.id);
        formData.set("avatarUrl", this.form.avatarUrl);
        formData.set("userName", this.form.userName);
        formData.set("role", this.form.role);
        formData.set("nickName", this.form.nickName);
        formData.set("gender", this.form.gender);
        formData.set("email", this.form.email);
        formData.set("phone", this.form.phone);
        formData.set("createTime", this.form.createTime);

        if (this.Urlavatar) {
          formData.set("file", this.Urlavatar, this.Urlavatar.name);
        }
        this.$axios.post("/User/SysUserUpdate",formData).then(res => {
        if (res.data.code == 200) {
          this.$message.success("修改成功")
          this.avatarUrl = ""
          this.dialogFormVisibles = false
          this.load()
        } else {
          this.$message.error("修改失败")
        }
      })
    } else {
      // 校验失败，不执行修改操作
    }
  });
},
  handelAdd(){
    this.dialogFormVisible = true
    this.avatarUrl =
        "http://101.43.223.224:8765/image/getImageById?id=" + row.avatarUrl;
    this.form = {}
  },
  handelEdit(row){
    // JSON.parse(JSON.stringify(row))
    this.form = JSON.parse(JSON.stringify(row))
    this.avatarUrl =
        "http://101.43.223.224:8765/image/getImageById?id=" + row.avatarUrl;
    // 图片回显
    this.dialogFormVisibles = true
  },
  handelEditck(row){
    this.avatarUrl =
        "http://101.43.223.224:8765/image/getImageById?id=" + row.avatarUrl;
    this.form = row
    this.dialogFormVisibleck = true
  },
  disableUser(row) {
      let obj = Object.assign({}, row)
      obj.disableUser = !!obj.disableUser
      this.updateUser(obj)
    },
  del(id){
    this.request.delete("/User/SysUserDelete" ,{
        params:{
         id:id
        }
      }).then(res =>{
      if(res){
        this.$message.success("删除成功")
        this.load()
      }else{
        this.$message.error("删除失败")
      }
    })
  },
  handleSelectionChange(val) {
    // console.log(val);
    this.multipleSelection = val
  },
  changeEnable(row) {
    const formData = new FormData()
    formData.set('id', row.id)
    formData.set('isDisable', row.isDisable)
      this.request.post("/User/updatescope", formData).then(res => {
        if (res) {
          this.$message.success("禁用成功")
        }
      })
    },
  // delBatch(){
  //   let ids = this.multipleSelection.map(item => item.id) // [{},{},{}] = [1,2,3]
  //   this.request.post("/user/del/batch", ids).then(res =>{
  //     if(res){
  //       this.$message.success("批量删除成功")
  //       this.load()
  //     }else{
  //       this.$message.error("批量删除失败")
  //     }
  //   })
  // },
  reset(){
    this.queryForm.userName = ""
    this.load()
  },
  handleSizeChange(pageSize){
    // console.log(pageSize);
    this.pageSize = pageSize;
    this.load()
  },handleCurrentChange(pageNum){
    // console.log(pageNum);
    this.pageNum = pageNum;
    this.load()
  },
//   exp() {
//     let user = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {}
//     axios({
//   method: 'get',
//   url:  'http://localhost:8081/user/export',
//   responseType: 'blob',
//   headers: { 'Authorization': 'Bearer ' + user.token }
// }).then((res) => {
//   let blob = new Blob( [res.data], { type: 'application/zip;charset=utf-8' });
//   console.log(res)
//   const f = res.headers["content-disposition"].split(";")[1].split("filename=")[1];
//   let fileName = decodeURIComponent(f)
//   if ('download' in document.createElement("a")) {
//     const link = document.createElement("a");
//     link.download = fileName;
//     link.style.display = 'none';
//     link.href = URL.createObjectURL(blob);
//     document.body.appendChild(link);
//     link.click();
//     URL.revokeObjectURL(link.href);
//     document.body.removeChild(link);
//   } else {
//     navigator.msSaveBlob(blob, fileName);
//   }
// })
// },
//   handleExcelImportSuccess(){
//     this.$message.success("导入成功")
//     this.load 
//   }
    }
}
</script>

<style>
.headerBg{
  background: #eee !important;
}
</style>